<?php

namespace app\comapi\controller;

use app\common\controller\Frontend;
use app\common\model\banxi\learn\LearnReadingArticle;
use app\common\model\banxi\learn\LearnReadingArticleAnswer;
use app\common\model\banxi\learn\LearnReadingArticleExtend;
use app\common\model\banxi\learn\LearnReadingArticleMarkWord;
use app\common\model\banxi\learn\LearnSayQuestionRecord;
use app\common\model\banxi\learn\LearnSkRecord;
use app\common\model\banxi\learn\LearnTwentyAntiForgetting;
use app\common\model\banxi\student\Student;
use app\common\model\banxi\trainer\Trainer;
use app\common\service\course\LexiconService;
use app\common\service\learn\LearnSkRecordService;
use think\facade\View;

/**
 * 配置
 */
class CommonPrint extends Frontend
{
    protected array $noNeedLogin = ['*'];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }


    /**
     * 文章单词打印
     */
    public function articleWordsPrint()
    {
        $articleId = $this->request->get('articleId', 0);
        $LearnReadingArticleModel = new LearnReadingArticle();
        $readingInfo = $LearnReadingArticleModel
            ->where(['id' => $articleId])
            ->find();
        if (!$readingInfo) {
            $this->fail('文章不存在');
        }
        $LearnReadingArticleMarkWordModel = new LearnReadingArticleMarkWord();
        $list = $LearnReadingArticleMarkWordModel->getByReadingArticleId($readingInfo);
        $this->ok('操作成功', ['words' => $list]);
    }

    /**
     * 文章打印
     */
    public function articlePrint()
    {
        $articleId = $this->request->get('articleId', 0);
        return View::fetch('articlePrint');
        //文章信息
        $LearnReadingArticleExtendModel = new LearnReadingArticleExtend();
        $readingInfo = $LearnReadingArticleExtendModel
            ->where(['readingArticleId' => $articleId])
            ->find();
        //问题习题
        $LearnReadingArticleAnswerModel = new LearnReadingArticleAnswer();
        $questionList = $LearnReadingArticleAnswerModel->where(['readingArticleId' => $articleId])->select();

        $this->ok('操作成功', ['data' => $readingInfo, 'questionList' => $questionList]);
    }

    /*
     * 上课记录打印
     * */
    public function skRecordPrint()
    {

        if ($this->request->isGet()) {
            return View::fetch();
        }
        $recordId = $this->request->post('recordId', 0);

        $LearnSkRecordModel = new LearnSkRecord();
        $recordInfo = $LearnSkRecordModel
            ->where(['id' => $recordId])
            ->find();
        if (!$recordInfo) {
            $this->fail('记录不存在');
        }
        //单词信息
        $LexiconService = new LexiconService();
        $words = $LexiconService->getSkRecordWords($recordId);
        //5个单词一分割，分割成多个数组
        $words = array_chunk($words->toArray(), 5);

        //学员信息
        $StudentModel = new Student();
        $studentInfo = $StudentModel->getById($recordInfo['studentId']);
        //教练信息
        $TrainerModel = new Trainer();
        $trainerInfo = $TrainerModel->getById($recordInfo['trainerId']);
        //21天抗遗忘日期
        $LearnTwentyAntiForgettingModel = new LearnTwentyAntiForgetting();
        $groupIdBySkRecord = $LearnTwentyAntiForgettingModel->getGroupIdBySkRecord($recordId);
        $antiForgettingDatas = $LearnTwentyAntiForgettingModel->listDateBySkRecord($recordId, $groupIdBySkRecord);
        //21天抗遗忘周期
        $LearnSkRecordService = new LearnSkRecordService();
        $days = $LearnSkRecordService->getAntiForgettingDay();
        $this->ok('操作成功', [
            'words' => $words,
            'printDate' => date('Y-m-d H:i'),
            'student' => $studentInfo,
            'teacher' => $trainerInfo,
            'antiForgettingDatas' => $antiForgettingDatas,
            'days' => $days
        ]);
    }


    public function sentenceQuestionPrint()
    {
        if ($this->request->isGet()) {
            return View::fetch();
        }

        $recordId = $this->request->param('recordId');
        if (!$recordId) {
            $this->fail('参数错误');
        }

        // 获取上课记录信息
        $recordInfo = $this->getSkRecordInfo($recordId);
        if (!$recordInfo) {
            $this->fail('记录不存在');
        }

        // 获取问题记录列表
        $list = $this->getQuestionRecordList($recordId);

        $sentenceCount = array_sum(array_map(function ($item) {
            return count($item['questionAnswerRecordList'] ?? []);
        }, $list));
        $sayTeachSentenceList = [];
        foreach ($list as $item) {
            $sayTeachSentenceList = array_merge($sayTeachSentenceList, $item['questionAnswerRecordList']);
        }
        // 提取核心词汇
        $coreVocabularyList = $this->extractCoreVocabulary($sayTeachSentenceList);

        $this->ok('操作成功', [
            'recordInfo' => $recordInfo,
            'list' => $list,
            'sentenceCount' => $sentenceCount,
            'coreVocabularyList' => $coreVocabularyList
        ]);
    }

    private function getSkRecordInfo($recordId)
    {
        $learnSkRecordModel = new LearnSkRecord();
        return $learnSkRecordModel
            ->with([
                'studentInfo' => function ($query) {
                    $query->field('id,name');
                },
                'trainerInfo' => function ($query) {
                    $query->field('id,name');
                }
            ])
            ->where(['id' => $recordId])
            ->find();
    }

    /**
     * 获取问题记录列表
     */
    private function getQuestionRecordList($recordId)
    {
        $learnSayQuestionRecordModel = new LearnSayQuestionRecord();
        return $learnSayQuestionRecordModel->with([
            'questionAnswerRecordList' => function ($query) {
                $query->alias('a')->join('banxi_say_teach_sentence b', 'a.sayTeachSentenceId = b.id')
                    ->where([['a.isCorrect', '>', -1]])
                    ->field('b.id,a.recordId,b.parentId,b.sentenceEn,b.sentenceZh,b.sentenceWordColor,b.coreVocabulary');
            },
            'sayTeachSentenceInfo' => function ($query) {
                $query->with([
                    'gradeInfo' => function ($query) {
                        $query->with([
                            'categoryInfo' => function ($query) {
                                $query->field('id,name');
                            }
                        ])->field('id,name,sayCategoryId');
                    }
                ])->field('id,name,gradeId');
            }
        ])
            ->where(['skRecordId' => $recordId])
            ->field('id,sayTeachSentenceId')
            ->select()
            ->toArray();
    }

    /**
     * 提取核心词汇列表
     */
    private function extractCoreVocabulary($sayTeachSentenceList)
    {
        $coreVocabularyList = [];

        // 收集所有核心词汇
        foreach ($sayTeachSentenceList as $sentence) {
            if (!empty($sentence['coreVocabularyList'])) {
                // 修复字段名：应该是 coreVocabulary 而不是 coreVocabularyList
                $vocabularies = $sentence['coreVocabularyList'];
                if (is_array($vocabularies)) {
                    $coreVocabularyList = array_merge($coreVocabularyList, $vocabularies);
                }
            }
        }

        // 按 wordEn 去重
        $uniqueVocabularyList = [];
        foreach ($coreVocabularyList as $vocabulary) {
            if (isset($vocabulary['wordEn']) && !isset($uniqueVocabularyList[$vocabulary['wordEn']])) {
                $uniqueVocabularyList[$vocabulary['wordEn']] = $vocabulary;
            }
        }

        // 返回索引数组而不是关联数组
        return array_values($uniqueVocabularyList);
    }

}